import axios from 'axios'
import { getQueryString } from '@/utils'
import Vue from 'vue'

const service = axios.create({
  baseURL: '',
  withCredentials: true,
  timeout: 5000 // request timeout
})

service.interceptors.request.use(
  config => {
    if (getQueryString('accessToken')) {
      config.headers['Authorization'] = 'Bearer ' + getQueryString('accessToken')
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const res = response.data
      if (res.status === 0) {
        return Promise.resolve(res)
      }
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          Vue.prototype.$message.error('登录过期')
      }
    }
    return Promise.reject(error.response.data)
  }
)

export default service